/**
 * @description 防抖函數
 */

import { onBeforeUnmount } from 'vue'

export default function useDebounce<T>(fn?: T, delay = 500): () => void {
  let timer: number | null = null

  onBeforeUnmount(() => {
    timer && clearTimeout(timer)
  })

  return function run(...args) {
    timer && clearTimeout(timer)

    timer = setTimeout(() => {
      if (typeof fn === 'function') {
        fn.apply(run, args)
      }
    }, delay)
  }
}
